package threadMethod;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author： pang-yun
 * @date： 2021-10-14 11:24
 * 功能目的 ：用于 观察 thread 的六种状态
 */

@Slf4j
public class ThreadState {
    public static void main(String[] args) throws InterruptedException {


        //未调用 状态是   new
        Thread t1 = new Thread(() -> {
            log.info("Running...");
        }, "t1");



        Thread t2=new Thread("t2"){
            @Override
            public void run() {
                while (true){}  // 分到时间片  没分到时间片 正在执行中  Runnable
            }
        };
        t2.start();

        Thread t3= new Thread("t3"){
            @Override
            public void run() {        // 最先执行完毕  状态是 terminated
                log.info("running....");
            }
        };
        t3.start();


        Thread t4 =new Thread("t4"){
            @SneakyThrows
            @Override
            public void run() {
                synchronized (ThreadState.class){  // timed_waiting  有时限的等待
                    TimeUnit.SECONDS.sleep(10);
                }
            }
        };
        t4.start();


        Thread t5 = new Thread("t5") {
            @Override
            public void run() {
                try {
                    t2.join();         // 等待 t2  因为 t2  一直在循环， 不会结束  所以  waiting
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        t5.start();


        Thread t6 =new Thread("t6"){
            @SneakyThrows
            @Override
            public void run() {
                synchronized (ThreadState.class){    // t4 已经拿到 锁， t6 不能拿到锁  状态是  Block
                    Thread.sleep(1000000);
                }
            }
        };

        t6.start();

        TimeUnit.SECONDS.sleep(1);

        log.info("t1 state: {}",t1.getState());
        log.info("t2 state: {}",t2.getState());
        log.info("t3 state: {}",t3.getState());
        log.info("t4 state: {}",t4.getState());
        log.info("t5 state: {}",t5.getState());
        log.info("t6 state: {}",t6.getState());

    }
}
